<!-- tree组件：支持关键词搜索、拖拽、右键添加、右键编辑
  @editNode" @createNode @deleteNode @clickNode

-->
<template>
  <div class="c-dragTree flex">
    <div class="c-dragTree-left" :style="treeStyle">
      <el-input :placeholder="lang.inputKeywords" v-if="showSearch" v-model="filterText" class="search" clearable />
      <el-tree
        :data="value"
        @node-click="handleLeftclick"
        @node-drag-start="handleDragStart"
        @node-drag-enter="handleDragEnter"
        @node-drag-leave="handleDragLeave"
        @node-drag-over="handleDragOver"
        @node-drag-end="handleDragEnd"
        @node-drop="handleDrop"
        @node-contextmenu="rightClick"
        :filter-node-method="filterNode"
        highlight-current
        default-expand-all
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        v-bind="treeConfig"
        ref="tree"
      >
        <div class="slot-t-node" slot-scope="{ node, data }">
          <!-- <span v-show="!data.isEdit"> -->
          <span :class="[data.id>= 99 ? 'slot-t-node--label' : '']">{{node.label}}</span>
          <!-- </span>
          <span v-show="data.isEdit">
            <el-input
              class="slot-t-input"
              size="mini"
              autofocus
              v-model="data.label"
              :ref="'slotTreeInput'+data.id"
              @blur.stop="NodeBlur(node,data)"
              @keydown.native.enter="NodeBlur(node,data)"
            ></el-input>
          </span> -->
        </div>
      </el-tree>
      <el-card class="box-card" ref="card" v-show="menuVisible">
        <div @click="addSameLevelNode()" v-if="!firstLevel && !fixNode" class="cardbtn">
          <i class="el-icon-circle-plus-outline"></i>{{ lang.addSameNode }}
        </div>
        <div class="add cardbtn" @click="addChildNode()">
          <i class="el-icon-circle-plus-outline"></i>{{ lang.addChildNode }}
        </div>
        <!-- <el-popconfirm :title="$t(`global.confirmDelete`)" @confirm="deleteNode()" placement="right" @click.stop> -->
        <div class="delete cardbtn" v-if="!firstLevel && !fixNode" @click="deleteNode()">
          <i class="el-icon-remove-outline"></i>{{ $t(`global.delete`) }}
        </div>
        <!-- </el-popconfirm> -->
        <div v-if="editButton" class="edit cardbtn" @click="editNode()">
          <i class="el-icon-edit"></i>{{ $t(`global.edit`) }}
        </div>
      </el-card>
    </div>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'dragTree',
  data() {
      return {
          currentData: '',
          currentNode: '',
          menuVisible: false,
          firstLevel: false,
          filterText: '',
          fixNode: false,
      }
  },
  mounted() {
    this.tree = this.$refs.tree;
    // console.log('tree-status', this.status);
  },
  methods: {
      // 鼠标左击事件
      handleLeftclick(data, node) {
          this.foo();
          this.currentData = data;
          this.currentNode = node
          this.$emit('clickNode', data, node);
      },
      saveNodeData(data) {
        this.$set(this.currentData, data);
      },
      // 鼠标右击事件
      rightClick(event, object, Node, element) {
          if (this.status !== 'edit') {
            return;
          }
          this.currentData = object
          this.currentNode = Node
          if (Node.level === 1 || object.nodeType === 'folder') {
              this.firstLevel = true
          } else {
              this.firstLevel = false
          }
          this.menuVisible = true
          document.addEventListener('click', this.foo)
          this.$refs.card.$el.style.left = event.clientX + 20 + 'px'
          this.$refs.card.$el.style.top = event.clientY -10 + 'px'
      },
      // 增加同级节点事件
      addSameLevelNode() {
          // let id = Math.ceil(Math.random() * 100)
          // var data = { id: id, label: '新增节点' }
          // this.$refs.tree.append(data, this.currentNode.parent)
          this.$emit('createNode', 'before', this.currentNode)
      },
      // 增加子级节点事件
      addChildNode() {
        console.log("🚀 ~ file: dragTree.vue:158 ~ addChildNode ~ this.maxLevel:", this.maxLevel, this.currentNode.level)
        if (this.currentNode.level >= this.maxLevel) {
          this.$message.error(`最多只支持${this.maxLevel}级！`)
          return false
        }
        this.$emit('createNode', 'inner', this.currentNode)
        // let id = Math.ceil(Math.random() * 100)
        // var data = { id: id, label: '新增节点' }
        // this.$refs.tree.append(data, this.currentNode)
      },
      // 删除节点
      deleteNode() {
          this.$refs.tree.remove(this.currentNode)
          this.$emit('deleteNode', this.currentData, this.currentNode)
          this.menuVisible = false
      },
      // 编辑节点
      editNode(data) {
          this.currentData = data ? data : this.currentData
          this.$emit('editNode', this.currentData, this.currentNode)
          // if (!this.currentData.isEdit) {
          //     this.$set(this.currentData, 'isEdit', true)
          // }
          // // 获取焦点
          // this.$nextTick(() => {
          //     this.$refs['slotTreeInput' + this.currentData.id].focus()
          // })
      },
      //  取消鼠标监听事件 菜单栏
      foo() {
          this.menuVisible = false
          //  要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
          document.removeEventListener('click', this.foo)
      },
      NodeBlur(Node, data) {
          if (data.label.length === 0) {
              this.$message.error(this.lang.menuNameNotEmpty)
              return false
          } else {
              if (data.isEdit) {
                  this.$set(data, 'isEdit', false)
              }
              this.$nextTick(() => {
                  this.$refs['slotTreeInput' + data.id].$refs.input.focus()
              })
          }
      },
      // 查询
      filterNode(value, data) {
          if (!value) return true
          return data.label.indexOf(value) !== -1
      },
      allowDrop(draggingNode, dropNode, type) {
          if (dropNode.data.nodeType === 'root' || dropNode.data.isRoot) {
              return type === 'inner'
          } else {
              return true
          }
      },
      setCurrentKey(id) {
        this.tree.setCurrentKey(id)
      },
      allowDrag(draggingNode) {
          return draggingNode.data.nodeType !== 'root' && !draggingNode.data.isRoot
      },
      handleDragStart(node, ev) {
          // console.log('drag start', node)
      },
      handleDragEnter(draggingNode, dropNode, ev) {
          // console.log('tree drag enter: ', dropNode.label)
      },
      handleDragLeave(draggingNode, dropNode, ev) {
          // console.log('tree drag leave: ', dropNode.label)
      },
      handleDragOver(draggingNode, dropNode, ev) {
          // console.log('tree drag over: ', dropNode.label)
      },
      handleDragEnd(draggingNode, dropNode, dropType, ev) {
          // console.log('tree drag end: ', dropNode && dropNode.label, dropType)
      },
      handleDrop(draggingNode, dropNode, dropType, ev) {
        // dropType: before after inner
        // console.log('tree drop: ', draggingNode, dropNode, dropType)
        this.$emit('drop', draggingNode, dropNode, dropType, ev)
      },
  },
  props: {
    treeConfig: {
      default() {
        return {
          nodeKey: 'nodeId',
          currentNodeKey: '',
          props: {
            label: 'label',
          }
        }
      }
    },
    showSearch: {
      default: false
    },
    editButton: {
      default: false
    },
    maxLevel: {
      default: 20
    },
    status: {
      default: 'edit' // edit read
    },
    value: {
      default() {
        return []
      }
    },
    width:  {
      default() {
        return '320px'
      }
    },
  },
  computed: {
  },
  watch: {
      filterText(val) {
          this.$refs.tree.filter(val)
      }
  },
  computed: {
    treeStyle() {
      return {
        width: this.width
      }
    },
    lang() {
      return {
        'zh-CN': {
          inputKeywords: '输入关键字',
          addSameNode: '增加同级',
          addChildNode: '增加子级',
          menuNameNotEmpty: '菜单名不可为空！',
        },
        'en-US': {
          inputKeywords: 'input keywords',
          addSameNode: 'add same node',
          addChildNode: 'add child node',
          menuNameNotEmpty: 'menu name can not empty!',
        }
      }[this.G_Locale]
    }
  }
}
</script>

<style scoped lang="less">
.c-dragTree {
  position: relative;
  height: 100%;
  // overflow: hidden;
  &-left {
    height: 100%;
    // overflow: auto;
  }
}
/* 点击节点时的选中颜色 */
.c-dragTree /deep/.el-tree-node.is-current > .el-tree-node__content {
  color: var(--primary-color)!important;
}

.c-dragTree /deep/ .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.c-dragTree /deep/ .el-icon-caret-right:before {
  content: "\e791";
  font-size: 18px;
}

.c-dragTree /deep/ .el-tree-node__expand-icon {
  margin-left: 15px;
  padding: 0px;
}

.c-dragTree /deep/ .el-tree-node__expand-icon.is-leaf {
  margin-left: 0px;
}
.c-dragTree /deep/ .el-tree-node__children {
  padding-left: 16px;
}

.c-dragTree /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.c-dragTree /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}
.c-dragTree /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.c-dragTree /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.c-dragTree /deep/ .el-tree-node:before {
  content: "";
  left: 10px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.c-dragTree /deep/ .el-tree-node:after {
  content: "";
  left: 10px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.c-dragTree /deep/ .el-tree-node:before {
  border-left: 1px dashed #ccc;
  bottom: 0px;
  height: 100%;
  top: -19px;
  width: 1px;
}

.c-dragTree /deep/ .el-tree-node:after {
  border-top: 1px dashed #ccc;
  height: 25px;
  top: 20px;
  width: 20px;
}

.el-tree-node :last-child:before {
  height: 40px;
}

// .c-dragTree {
//   margin: 10px;
// }
.c-dragTree /deep/ .el-tree .el-tree-node {
  position: relative;
}
.c-dragTree /deep/ .el-tree-node .el-tree-node__content {
  height: 34px;
  // padding-left: 0px !important;
  border: none;
}
.c-dragTree /deep/ .el-tree-node .el-tree-node__content::before {
  border-left: 1px dashed #ccc;
  height: 100%;
  top: 0;
  width: 1px;
  margin-left: 1px;
  margin-top: 0px;
  z-index: 8;
}
.c-dragTree
  /deep/
  .el-tree-node
  .el-tree-node__children
  .el-tree-node__content::before {
  border-left: 0px dashed #ccc;
  height: 100%;
  top: 0;
  width: 1px;
  margin-left: 1px;
  margin-top: 0px;
  z-index: 8;
}

.c-dragTree /deep/ .el-tree-node .el-tree-node__content::after {
  border-top: 1px dashed #ccc;
  height: 1px;
  top: 18px;
  width: 13px;
  margin-left: 1px;
  z-index: 8;
}

.c-dragTree
  /deep/
  .el-tree-node
  .el-tree-node__children
  .el-tree-node__content::after {
  border-top: 0px dashed #ccc;
}

.c-dragTree .el-tree-node .el-tree-node__content::before,
.c-dragTree .el-tree-node .el-tree-node__content::after {
  content: "";
  position: absolute;
  right: auto;
}

.text {
  font-size: 14px;
}
.item {
  padding: 18px 0;
}
.search {
  cursor: pointer;
}

.box-card {
  position: fixed;
  width: 150px;
  z-index: 1000;
}
/deep/.el-table__placeholder {
  padding-left: 8px;
}
/deep/.el-card__body {
  padding: 0 16px 6px!important;
  .cardbtn {
      cursor: pointer;
      padding: 10px 0;
      border-bottom: 1px solid #e7e7e7;
      > i {
        padding-right: 8px;
      }
      &:hover {
          color: var(--primary-color);
      }
  }
}
</style>
